import { Row, Col } from "antd";
import { useEffect, useState } from "react";
import { getTaskCategoryList, useTaskRoot } from "../../api";
import FormRender, { useForm, Error as FormRenderError } from "form-render";
import { StepProps } from ".";

let res: (v: any) => void;
let rej: (v: any) => void;
const Step4 = ({ validator }: StepProps) => {
    const taskRoot = useTaskRoot();
    const form = useForm();
    const [schema, setSchema] = useState<{}>();

    validator.current = (): Promise<any> => {
        form.submit();
        return new Promise<any>((resolve, reject) => {
            res = resolve;
            rej = reject;
        });
    }

    const onFinish = (formData: any, errors: FormRenderError[]) => {
        if (errors && errors.length) {
            rej(errors);
        } else {
            res(formData);
        }
    }

    useEffect(() => {
        (async () => {
            const categoryGroups = await getTaskCategoryList(taskRoot);
            const enumNames = [], enumValues = [];
            for (const group of categoryGroups) {
                const { id, component: { name } } = group;
                enumValues.push(id);
                enumNames.push(name);
            }
            setSchema({
                type: "object",
                properties: {
                    "parentGroupId": {
                        order: 1,
                        type: "string",
                        title: "任务类别",
                        required: true,
                        enum: enumValues,
                        enumNames: enumNames,
                        widget: 'select',
                    },
                    "name": {
                        order: 2,
                        type: "string",
                        title: "任务名称",
                        required: true,
                    },
                    "comments": {
                        order: 3,
                        type: "string",
                        format: "textarea",
                        title: "任务说明",
                    }
                }
            })
        })();
    }, [taskRoot]);

    return (<>
        <Row gutter={24}>
            <Col push={6} span={12} >
                <p>
                    <h1>保存任务配置</h1>
                    <span>请选择任务类别，并填写任务名称和说明。</span>
                </p>
            </Col>
            <Col span={6}></Col>
            <Col push={6} span={12}>
                <FormRender schema={schema} form={form} onFinish={onFinish} />
            </Col>
        </Row>
    </>)
};

export default Step4;